<script setup lang="ts">
// 导入全局状态
import { useUserStore } from '@/stores/user'
import { getCart, selectoneCart, updateNum } from '@/api/cart'
import { onMounted, ref } from 'vue'
import type { Ref } from 'vue'
import { showToast } from 'vant'

const user = useUserStore()

// console.log(user);

interface iPro {
  cartid: string
  discount: number
  flag: boolean
  img1: string
  num: number
  originprice: number
  proid: string
  proname: string
  userid: string
}
const proList: Ref<iPro[]> = ref([])

onMounted(() => {
  getCart({ userid: user.userid }).then(res => {
    // console.log(res.data);
    proList.value = res.data.data
  })
})

// 更新购物车数量
function updateUnmClick(type: string, item: iPro) {
  if (type == '+') {
    item.num++
  } else {
    // console.log(item.num);

    item.num = item.num > 1 ? item.num - 1 : 1
  }

  updateNum({
    cartid: item.cartid,
    num: String(item.num)
  }).then(res => {
    console.log(res);
    showToast(res.data.message)
  })
}

// 更新购物车选中状态
function changeCheckBox(item: iPro, e: any) {
  // console.log(e);
  selectoneCart({ cartid: item.cartid, flag: e }).then(res => {
    // console.log(res);
    showToast(res.data.message)
  })
}
</script>
<template>
  <div class="box">
    <header class="header"> 购物车 </header>
    <div class="content">
      <van-card v-for="item in proList" :key="item.proid" :num="item.num" :price="item.originprice" :title="item.proname">
        <template #thumb>
          <div class="imgBox">
            <van-checkbox class="img-checkbox" @change="changeCheckBox(item, $event)" v-model="item.flag"></van-checkbox>
            <van-image width="80" height="80" :src="item.img1"></van-image>
          </div>
        </template>
        <template #footer>
          <van-button size="mini" class="changBtn" @click="updateUnmClick('+', item)">+</van-button>
          <van-button size="mini" class="changBtn" @click="updateUnmClick('-', item)">-</van-button>
        </template>
      </van-card>


    </div>

    <van-submit-bar :price="3050" button-text="提交订单">
      <van-checkbox>全选</van-checkbox>
      <template #tip>
        你的收货地址不支持配送, <span>修改地址</span>
      </template>
    </van-submit-bar>


  </div>
</template>
<style lang="scss" scoped>
.changBtn {
  padding: 0 10px;
}

.imgBox {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.img-checkbox {
  /* margin-right: 10px; */
  padding-right: 10px;
}

.van-submit-bar {
  bottom: 51px;
}

.content {
  padding-bottom: 100px;
}
</style>
